/**
 *  Copyright � 2010 Digia Plc
 *  Copyright � 2010 Nokia Corporation
 *
 *  All rights reserved.
 *
 *  Nokia and Nokia Connecting People are registered trademarks of
 *  Nokia Corporation.
 *  Java and all Java-based marks are trademarks or registered
 *  trademarks of
 *  Sun Microsystems, Inc. Other product and company names
 *  mentioned herein may be
 *  trademarks or trade names of their respective owners.
 *
 *
 *  Subject to the conditions below, you may, without charge:
 *
 *  �  Use, copy, modify and/or merge copies of this software and
 *     associated documentation files (the "Software")
 *
 *  �  Publish, distribute, sub-licence and/or sell new software
 *     derived from or incorporating the Software.
 *
 *
 *  This file, unmodified, shall be included with all copies or
 *  substantial portions
 *  of the Software that are distributed in source code form.
 *
 *  The Software cannot constitute the primary value of any new
 *  software derived
 *  from or incorporating the Software.
 *
 *  Any person dealing with the Software shall not misrepresent
 *  the source of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
 *  KIND, EXPRESS OR IMPLIED,
 *  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A
 *  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT
 *  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 *  WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 *  CONNECTION WITH THE
 *  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var currentWeek = null;
var availableWeeks = null;
var maxConsumption = null;
var weekData = null;
var startWeek = null;
var startYear = null;

/**
 * Set-up function for EnergyView
 *
 * @return boolean
 */
function onStartUp() {
    currentWeek = 0;
    startWeek = weekNumber();
    startYear = yearNumber();
    availableWeeks = weekData.length;
    maxConsumption = getMaxConsumption();
    histogram.maxValue = maxConsumption;
    return showWeek( currentWeek );
}

/**
 * Changes current week (changed to represent years in HomeControlSystem)
 *
 * @param weekID The index of the dataset in data table
 * @return boolean
 */
function showWeek(weekID) {
    if (weekID < 0) weekID = weekData.length - 1;
    if (weekID >= weekData.length) weekID = 0;
    currentWeek = weekID;
    var yearToUse = startYear - weekID;
    weekYear.text = "Year " + yearToUse;
    histogram.setValues( weekData[weekID] );
    return true;
}

/**
 * Finds and return the largest consumption
 *
 * @return real
 */
function getMaxConsumption() {
    var a = 0;
    var b = 0;
    var currentMax = 0;
    for(a = 0; a < availableWeeks; a++) {
        for(b = 0; b < 7; b++) {
            if (weekData[a][b][0] > currentMax) currentMax = weekData[a][b][0];
        }
    }
    return currentMax;
}


/**
 * Expands Date class (Picked from the Internet)
 *
 * @return int
 */
Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

/**
 * Gets the number of current week
 *
 * @return int
 */
function weekNumber() {
    var theDate = new Date();
    return theDate.getWeek();
}

/**
 * Gets the number of current year
 *
 * @return int
 */
function yearNumber() {
    var theDate = new Date();
    return theDate.getFullYear();
}

/**
 * Counts the width for label items (month initials on EnergyView)
 *
 * @return real
 */
function columnWidth() {
    var amount = histogram.countVisible();
    return Math.round( ( (histogram.width/(2*histogram.spacing)) - (histogram.spacing*(amount-1)) ) / amount );
}


/**
 * SQL FUNCTIONS
 */

/**
 * Checks whether sauna is on
 *
 * @return bool
 */
function isSaunaOn() {
    var db = openDatabaseSync("HomeControl", "1.0", "CoDe Qt Quick application", 1000000);
    var saunaOn = false;
    db.transaction(
        function(tx) {
            //Updating information
            saunaOn = tx.executeSql('SELECT saunaOn FROM Sauna').rows.item(0).saunaOn;
        }
    )
    return saunaOn;
}

/**
 * Gets sauna temperature
 *
 * @return Nothing
 */
function getSaunaTemperature() {
    var db = openDatabaseSync("HomeControl", "1.0", "CoDe Qt Quick application", 1000000);
    var temperature = -1
    db.transaction(
        function(tx) {
            //Updating information
            temperature = tx.executeSql('SELECT temperature FROM Sauna').rows.item(0).temperature;
        }
    )
    return temperature;
}

/**
 * Counts the total consumption and adds the values to the table
 *
 * @return Nothing
 */
function loadConsumption() {
    var db = openDatabaseSync("HomeControl", "1.0", "CoDe Qt Quick application", 1000000);
    db.transaction(
        function(tx) {
            var info = tx.executeSql("SELECT COUNT(*) as allrooms, SUM(light) as lightsum FROM RoomTable");
            var info2 = tx.executeSql("SELECT volume, mute, temp FROM RoomTable");
            var usedVolume = 0;
            var usedHeat = 0;
            var heatingPower = 80; //  W/m^2
            var houseArea = 120; //  m^2
            for (var i=0; i < info2.rows.length; i++) {
                if (info2.rows.item(i).mute == "false") usedVolume += parseInt(info2.rows.item(i).volume);
                usedHeat += parseInt(info2.rows.item(i).temp);
            }
            var saunaWatts = ( isSaunaOn() ) ? ((getSaunaTemperature()/120)*6000) : 0;
            var machines = 12500;
            var misc = 8350;
            var whole = 0;
            whole += Math.round(info.rows.item(0).lightsum*(3/5)*3+6000);
            whole += Math.round(usedVolume*(1.2)+5000);
            whole += machines;
            whole += misc;
            whole += saunaWatts;
            whole += Math.round( (usedHeat/(info.rows.item(0).allrooms*30)) * 80 * 120 ) + 4000;

            var theValues = Array();

            var maxPercentage = 0;

            lightsW.text = " " + Math.round(info.rows.item(0).lightsum*(3/5)*3+6000)/1000;
            theValues[0] = Array();
            theValues[0][0] = Math.round( ((info.rows.item(0).lightsum*(3/5)*3+6000)/whole) * 100 );
            if (theValues[0][0] > maxPercentage) maxPercentage = theValues[0][0];
            theValues[0][1] = "Lights";

            avW.text = " " + Math.round(usedVolume*(1.2)+5000)/1000;
            theValues[1] = Array();
            theValues[1][0] = Math.round( ((usedVolume*(1.2)+5000)/whole) * 100 );
            if (theValues[1][0] > maxPercentage) maxPercentage = theValues[1][0];
            theValues[1][1] = "AV";

            machinesW.text = " " + Math.round(machines)/1000;
            theValues[2] = Array();
            theValues[2][0] = Math.round( ((machines)/whole) * 100 );
            if (theValues[2][0] > maxPercentage) maxPercentage = theValues[2][0];
            theValues[2][1] = "Appliances";

            saunaW.text = " " + saunaWatts/1000;
            theValues[3] = Array();
            theValues[3][0] = Math.round( (saunaWatts/whole) * 100 );
            if (theValues[3][0] > maxPercentage) maxPercentage = theValues[3][0];
            theValues[3][1] = "Sauna";

            heatingW.text = " " + Math.round( (usedHeat/(info.rows.item(0).allrooms*30)) * 80 * 120 + 4000 )/1000;
            theValues[4] = Array();
            theValues[4][0] = Math.round( (( (usedHeat/(info.rows.item(0).allrooms*30)) * 80 * 120 + 4000 )/whole) * 100 );
            if (theValues[4][0] > maxPercentage) maxPercentage = theValues[4][0];
            theValues[4][1] = "Heating";

            miscW.text = " " + Math.round(misc)/1000;
            theValues[5] = Array();
            theValues[5][0] = Math.round( ((misc)/whole) * 100 );
            if (theValues[5][0] > maxPercentage) maxPercentage = theValues[5][0];
            theValues[5][1] = "Misc.";

            histogram2.maxValue = maxPercentage;
            histogram2.setValues( theValues );

            total.text = (whole/1000);
        }
    )
}






/**
 * Monthly energy consumption data.
 */
weekData = Array();
// Week #1                     // Week #2                     // Week #3
weekData[0] = Array();         weekData[1] = Array();         weekData[2] = Array();
weekData[0][0] = Array();      weekData[1][0] = Array();      weekData[2][0] = Array();
weekData[0][0][0] = 183;       weekData[1][0][0] = 360;       weekData[2][0][0] = 300;
weekData[0][0][1] = "M";       weekData[1][0][1] = "M";       weekData[2][0][1] = "M";
weekData[0][1] = Array();      weekData[1][1] = Array();      weekData[2][1] = Array();
weekData[0][1][0] = 280;       weekData[1][1][0] = 260;       weekData[2][1][0] = 282;
weekData[0][1][1] = "T";       weekData[1][1][1] = "T";       weekData[2][1][1] = "T";
weekData[0][2] = Array();      weekData[1][2] = Array();      weekData[2][2] = Array();
weekData[0][2][0] = 346;       weekData[1][2][0] = 250;       weekData[2][2][0] = 265;
weekData[0][2][1] = "W";       weekData[1][2][1] = "W";       weekData[2][2][1] = "W";
weekData[0][3] = Array();      weekData[1][3] = Array();      weekData[2][3] = Array();
weekData[0][3][0] = 330;       weekData[1][3][0] = 265;       weekData[2][3][0] = 288;
weekData[0][3][1] = "T";       weekData[1][3][1] = "T";       weekData[2][3][1] = "T";
weekData[0][4] = Array();      weekData[1][4] = Array();      weekData[2][4] = Array();
weekData[0][4][0] = 285;       weekData[1][4][0] = 280;       weekData[2][4][0] = 180;
weekData[0][4][1] = "F";       weekData[1][4][1] = "F";       weekData[2][4][1] = "F";
weekData[0][5] = Array();      weekData[1][5] = Array();      weekData[2][5] = Array();
weekData[0][5][0] = 270;       weekData[1][5][0] = 313;       weekData[2][5][0] = 130;
weekData[0][5][1] = "S";       weekData[1][5][1] = "S";       weekData[2][5][1] = "S";
weekData[0][6] = Array();      weekData[1][6] = Array();      weekData[2][6] = Array();
weekData[0][6][0] = 290;       weekData[1][6][0] = 330;       weekData[2][6][0] = 120;
weekData[0][6][1] = "S";       weekData[1][6][1] = "S";       weekData[2][6][1] = "S";
weekData[0][7] = Array();      weekData[1][7] = Array();      weekData[2][7] = Array();
weekData[0][7][0] = 183;       weekData[1][7][0] = 360;       weekData[2][7][0] = 300;
weekData[0][7][1] = "M";       weekData[1][7][1] = "M";       weekData[2][7][1] = "M";
weekData[0][8] = Array();      weekData[1][8] = Array();      weekData[2][8] = Array();
weekData[0][8][0] = 280;       weekData[1][8][0] = 260;       weekData[2][8][0] = 282;
weekData[0][8][1] = "T";       weekData[1][8][1] = "T";       weekData[2][8][1] = "T";
weekData[0][9] = Array();      weekData[1][9] = Array();      weekData[2][9] = Array();
weekData[0][9][0] = 346;       weekData[1][9][0] = 250;       weekData[2][9][0] = 265;
weekData[0][9][1] = "W";       weekData[1][9][1] = "W";       weekData[2][9][1] = "W";
weekData[0][10] = Array();     weekData[1][10] = Array();     weekData[2][10] = Array();
weekData[0][10][0] = 330;      weekData[1][10][0] = 265;      weekData[2][10][0] = 288;
weekData[0][10][1] = "T";      weekData[1][10][1] = "T";      weekData[2][10][1] = "T";
weekData[0][11] = Array();     weekData[1][11] = Array();     weekData[2][11] = Array();
weekData[0][11][0] = 285;      weekData[1][11][0] = 280;      weekData[2][11][0] = 180;
weekData[0][11][1] = "F";      weekData[1][11][1] = "F";      weekData[2][11][1] = "F";

